#include "DynLibManager.h"
#include "DynLib.h"

namespace OCPP
{
    //-----------------------------------------------------------------------
    template<> DynLibManager* CSingleton<DynLibManager>::msSingleton = 0;
    DynLibManager* DynLibManager::getSingletonPtr(void)
    {
        return msSingleton;
    }
    //-----------------------------------------------------------------------
    DynLibManager& DynLibManager::getSingleton(void)
    {  
        assert( msSingleton );  return ( *msSingleton );  
    }
    //-----------------------------------------------------------------------
    DynLibManager::DynLibManager()
    {
    }
    //-----------------------------------------------------------------------
    DynLib* DynLibManager::load( const String& filename)
    {
        DynLibList::iterator i = mLibList.find(filename);
        if (i != mLibList.end())
        {
            return i->second;
        }
        else
        {
            DynLib* pLib = CORE_NEW DynLib(filename);
            pLib->load();        
            mLibList[filename] = pLib;
            return pLib;
        }
    }
    //-----------------------------------------------------------------------
    void DynLibManager::unload(DynLib* lib)
    {
        DynLibList::iterator i = mLibList.find(lib->getName());
        if (i != mLibList.end())
        {
            mLibList.erase(i);
        }
        lib->unload();
        CORE_DELETE lib;
    }
    //-----------------------------------------------------------------------
    DynLibManager::~DynLibManager()
    {
        // Unload & delete resources in turn
        for( DynLibList::iterator it = mLibList.begin(); it != mLibList.end(); ++it )
        {
            it->second->unload();
            CORE_DELETE it->second;
        }

        // Empty the list
        mLibList.clear();
    }
}
